package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-10-28
 * Time: 20:08
 */
class Singleton1 {
    private static volatile Singleton1 instance = null;
    private Singleton1(){}

    //存在线程安全问题
    //1.双层if
    //2.synchronized 加锁
    //3.volatile 防止指令重排序
    public static Singleton1 getInstance(){
        if (instance == null){
            synchronized (Singleton1.class){
                if (instance == null){
                    return new Singleton1();
                }
            }
        }
        return instance;
    }
}

//单例模式 懒汉模式
public class Demo2 {
    public static void main(String[] args) {
        Singleton1 instance = Singleton1.getInstance();
    }
}
